package dao;

import model.Faculty;
import org.hibernate.Session;
import util.HibernateUtil;

import java.util.ArrayList;
import java.util.List;


public class FacultyDaoImpl implements FacultyDao {
    Session session;
    public void createFaculty(Faculty faculty) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.save(faculty);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public Faculty readFaculty(int index) {
        Faculty faculty = null;
        try{
            session = HibernateUtil.getSession().openSession();
            faculty = (Faculty) session.load(Faculty.class,index);

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
        return faculty;
    }

    public void updateFaculty(Faculty faculty) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.update(faculty);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public void deleteFaculty(Faculty faculty) {

        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.delete(faculty);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public List<Faculty> getAllFaculties() {
        Session session = null;
        List<Faculty> faculties = new ArrayList<Faculty>();
        try {
            session = HibernateUtil.getSession().openSession();
            faculties = session.createCriteria(Faculty.class).list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return faculties;
    }
}
